<template>
  <div class="draw-goal-container">
    <!-- 及格线设置 -->
    <div v-if="chartType === 'achievement-scatter'" class="pass-line-setting">
      <el-form-item label="及格线设置：" class="pass-line-form-item">
                 <el-input
           :model-value="props.achievementStandard"
           type="number"
           placeholder="请输入达成标准（0-1之间）"
           style="width: 200px;"
           :min="0"
           :max="1"
           :step="0.01"
           @input="handlePassLineChange"
         >
          
        </el-input>
      </el-form-item>
    </div>

    <!-- 柱状图：课程目标评价达成值 -->
    <div v-if="chartType === 'achievement-bar'" class="chart-container">
      <div class="chart-header">
        <h4>课程目标达成值</h4>
        <el-button 
          type="primary" 
          size="small" 
          @click="copyChartImage('achievement-bar-chart')"
          :icon="CopyDocument"
        >
          复制图片
        </el-button>
      </div>
      <div ref="achievementBarChartRef" class="chart" id="achievement-bar-chart"></div>
    </div>
    
    <!-- 散点图：课程目标达成分布图 -->
    <div v-if="chartType === 'achievement-scatter'" class="chart-container">
      <div class="chart-header">
        <h4>课程目标达成分布图</h4>
        <el-button 
          type="primary" 
          size="small" 
          @click="copyAllScatterCharts"
          :icon="CopyDocument"
        >
          复制所有图片
        </el-button>
      </div>
      <div v-for="(goal, goalIndex) in goalResults" :key="goalIndex" class="scatter-chart-item">
        <div class="scatter-chart-header">
          <h5>课程目标{{ goal.number }}达成分布图</h5>
          <el-button 
            type="primary" 
            size="small" 
            @click="copyChartImage(`scatter-chart-${goal.number}`)"
            :icon="CopyDocument"
          >
            复制图片
          </el-button>
        </div>
        <div 
          :ref="el => scatterChartRefs[goalIndex] = el" 
          :id="`scatter-chart-${goal.number}`"
          class="scatter-chart"
        ></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { CopyDocument } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 定义props
const props = defineProps({
  goalResults: {
    type: Array,
    default: () => []
  },
  studentData: {
    type: Array,
    default: () => []
  },
  evaluationMethods: {
    type: Array,
    default: () => []
  },
  dataHeaders: {
    type: Array,
    default: () => []
  },
  achievementStandard: {
    type: Number,
    default: 0.6
  },
  chartType: {
    type: String,
    required: true,
    validator: (value) => ['achievement-bar', 'achievement-scatter'].includes(value)
  }
})

// 定义emit
const emit = defineEmits(['update:achievementStandard'])

// 图表引用
const achievementBarChartRef = ref(null)
const scatterChartRefs = ref([])

// 图表实例
let barChart = null
let scatterCharts = []

// 及格线设置 - 使用props中的达成标准
const passLineValue = computed(() => props.achievementStandard)

// 计算每个学生每个目标的达成度
const calculateStudentGoalAchievements = () => {
  if (!props.studentData.length || !props.evaluationMethods.length || !props.goalResults.length) {
    console.log('缺少必要数据:', {
      studentDataLength: props.studentData.length,
      evaluationMethodsLength: props.evaluationMethods.length,
      goalResultsLength: props.goalResults.length
    })
    return []
  }
  
  const studentAchievements = []
  
  props.studentData.forEach((studentRow, studentIndex) => {
    const studentGoalAchievements = []
    
    // 计算每个课程目标的达成度
    props.goalResults.forEach((goal, goalIndex) => {
      let totalScore = 0      // 分子：学生实际得分
      let totalMaxScore = 0   // 分母：满分
      
      props.evaluationMethods.forEach((method, methodIndex) => {
        const methodName = method.methodName
        const methodWeight = method.percentage / 100 // 评价方法权重（如20% = 0.2）
        const goalWeight = method.goalWeights[goalIndex] / 100 // 课程目标在该评价方法中的权重（如30% = 0.3）
        
        // 获取学生在该评价方法中该课程目标的分数
        const headerName = `${methodName}$目标${goal.number}`
        const scoreIndex = props.dataHeaders.indexOf(headerName)
        const studentScore = parseFloat(studentRow[scoreIndex]) || 0
        
        // 计算该评价方法中该课程目标的满分
        const maxScore = goalWeight * 100 // 例如：30% * 100 = 30分
        
        // 累加分子：学生实际得分 * 评价方法权重
        totalScore += studentScore * methodWeight
        
        // 累加分母：满分 * 评价方法权重
        totalMaxScore += maxScore * methodWeight
      })
      
      // 计算达成度：实际得分 / 满分
      const achievement = totalMaxScore > 0 ? totalScore / totalMaxScore : 0
      
      studentGoalAchievements.push({
        goalNumber: goal.number,
        achievement: achievement
      })
    })
    
    studentAchievements.push({
      studentIndex: studentIndex + 1,
      goalAchievements: studentGoalAchievements
    })
  })
  
  return studentAchievements
}

// 绘制柱状图
const drawBarChart = () => {
  if (!achievementBarChartRef.value) return
  
  // 销毁旧图表
  if (barChart) {
    barChart.dispose()
  }
  
  // 设置柱状图的纵横比为4:3
  const container = achievementBarChartRef.value
  const containerWidth = container.offsetWidth
  const containerHeight = (containerWidth * 3) / 4
  container.style.height = `${containerHeight}px`
  
  // 准备数据
  const goalNumbers = props.goalResults.map(goal => goal.number)
  const achievementValues = props.goalResults.map(goal => parseFloat(goal.achievementValue))
  
  // 创建图表
  barChart = echarts.init(achievementBarChartRef.value)
  
  const option = {
    title: {
      text: '课程目标达成值',
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 32,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const data = params[0]
        return `课程目标${data.name}<br/>达成值：${data.value.toFixed(2)}`
      }
    },
    grid: {
      left: '8%',
      right: '8%',
      bottom: '12%',
      top: 60,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: goalNumbers,
      name: '课程目标',
      nameLocation: 'center',
      nameGap: 30,
      nameTextStyle: {
        fontSize: 24
      },
      axisLabel: {
        fontSize: 20
      },
      axisLine: {
        lineStyle: {
          color: '#333'
        }
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      name: '达成度',
      nameLocation: 'middle',
      nameGap: 40,
      nameTextStyle: {
        fontSize: 24
      },
      axisLabel: {
        fontSize: 20
      },
      min: 0,
      max: 1,
      interval: 0.1,
      axisLine: {
        lineStyle: {
          color: '#333'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#e0e0e0',
          width: 1
        }
      }
    },
    series: [
      {
        name: '达成值',
        type: 'bar',
        data: achievementValues,
        itemStyle: {
          color: '#87CEEB',
          borderWidth: 0
        },
        emphasis: {
          itemStyle: {
            color: '#5F9EA0'
          }
        },
        label: {
          show: true,
          position: 'top',
          formatter: function(params) {
            return params.value.toFixed(2)
          },
          fontSize: 20,
          color: '#333'
        }
      }
    ]
  }
  
  barChart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    if (barChart) {
      barChart.resize()
    }
  })
}

// 绘制散点图
const drawScatterChart = () => {
  // 销毁旧图表
  scatterCharts.forEach(chart => {
    if (chart) {
      chart.dispose()
    }
  })
  scatterCharts = []
  
  // 计算学生达成度数据
  const studentAchievements = calculateStudentGoalAchievements()
  
  if (studentAchievements.length === 0) {
    return
  }
  
  // 为每个课程目标创建单独的散点图
  props.goalResults.forEach((goal, goalIndex) => {
    const chartRef = scatterChartRefs.value[goalIndex]
    if (!chartRef) return
    
    // 设置图表的纵横比为4:3
    const containerWidth = chartRef.offsetWidth
    const containerHeight = (containerWidth * 3) / 4
    chartRef.style.height = `${containerHeight}px`
    
    // 创建图表
    const chart = echarts.init(chartRef)
    scatterCharts.push(chart)
    
    // 准备该课程目标的数据
    const data = studentAchievements.map(student => [
      student.studentIndex,
      student.goalAchievements[goalIndex].achievement
    ])
    
    // 调试信息：打印计算得到的散点值
    // console.log(`课程目标${goal.number}的散点数据:`, data)
    // console.log(`课程目标${goal.number}的学生数量:`, data.length)
    // console.log(`课程目标${goal.number}的达成度范围:`, {
    //   min: Math.min(...data.map(d => d[1])),
    //   max: Math.max(...data.map(d => d[1])),
    //   avg: data.reduce((sum, d) => sum + d[1], 0) / data.length
    // })
    
    const option = {
      title: {
        text: `课程目标${goal.number}达成分布图`,
        left: 'center',
        top: 10,
        textStyle: {
          fontSize: 32,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          return `学生${params.value[0]}<br/>达成度：${params.value[1].toFixed(2)}`
        }
      },
      grid: {
        left: '8%',
        right: '8%',
        bottom: '12%',
        top: 60,
        containLabel: true
      },
      xAxis: {
        type: 'value',
        name: '人数',
        nameLocation: 'center',
        nameGap: 30,
        nameTextStyle: {
          fontSize: 24
        },
        axisLabel: {
          fontSize: 20
        },
        axisLine: {
          lineStyle: {
            color: '#333'
          }
        },
        splitLine: {
          lineStyle: {
            color: '#e0e0e0',
            width: 1
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '达成度',
        nameLocation: 'middle',
        nameGap: 40,
        nameTextStyle: {
          fontSize: 24
        },
        axisLabel: {
          fontSize: 20
        },
        min: 0,
        max: 1,
        interval: 0.1,
        axisLine: {
          lineStyle: {
            color: '#333'
          }
        },
        splitLine: {
          lineStyle: {
            color: '#e0e0e0',
            width: 1
          }
        }
      },
      series: [
        {
          name: `课程目标${goal.number}`,
          type: 'scatter',
          data: data,
          symbolSize: 8,
          itemStyle: {
            color: '#4169E1'
          },
          emphasis: {
            itemStyle: {
              color: '#1E90FF',
              borderColor: '#fff',
              borderWidth: 2
            }
          },
                     markLine: {
             silent: true,
             lineStyle: {
               color: '#FF0000',
               width: 2
             },
                          data: [
                {
                  yAxis: passLineValue.value,
                  label: {
                    formatter: `及格线(${passLineValue.value.toFixed(2)})`,
                    position: 'insideEndTop',
                    fontSize: 16
                  }
                }
              ]
           }
        }
      ]
    }
    
    chart.setOption(option)
  })
  
  // 响应式调整
  window.addEventListener('resize', () => {
    scatterCharts.forEach(chart => {
      if (chart) {
        chart.resize()
      }
    })
  })
}

// 复制图表图片
const copyChartImage = async (chartId) => {
  try {
    const chartElement = document.getElementById(chartId)
    if (!chartElement) {
      ElMessage.error('图表元素未找到')
      return
    }
    
    // 使用html2canvas将图表转换为图片
    const html2canvas = await import('html2canvas')
    const canvas = await html2canvas.default(chartElement, {
      backgroundColor: '#ffffff',
      scale: 2, // 提高图片质量
      useCORS: true
    })
    
    // 将canvas转换为blob
    canvas.toBlob(async (blob) => {
      try {
        // 创建ClipboardItem
        const clipboardItem = new ClipboardItem({
          'image/png': blob
        })
        
        // 复制到剪贴板
        await navigator.clipboard.write([clipboardItem])
        ElMessage.success('图片已复制到剪贴板')
      } catch (err) {
        // 降级方案：下载图片
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `${chartId}.png`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
        ElMessage.success('图片已下载')
      }
    }, 'image/png')
    
  } catch (error) {
    console.error('复制图片失败:', error)
    ElMessage.error('复制图片失败，请检查html2canvas库是否正确安装')
  }
}

// 复制所有散点图
const copyAllScatterCharts = async () => {
  try {
    const chartIds = props.goalResults.map(goal => `scatter-chart-${goal.number}`)
    let successCount = 0
    
    for (const chartId of chartIds) {
      try {
        await copyChartImage(chartId)
        successCount++
        // 添加延迟避免剪贴板冲突
        await new Promise(resolve => setTimeout(resolve, 500))
      } catch (error) {
        console.error(`复制图表 ${chartId} 失败:`, error)
      }
    }
    
    if (successCount > 0) {
      ElMessage.success(`成功复制 ${successCount} 张图片到剪贴板`)
    } else {
      ElMessage.error('复制图片失败')
    }
  } catch (error) {
    console.error('复制所有散点图失败:', error)
    ElMessage.error('复制所有散点图失败')
  }
}

// 处理及格线输入变化
const handlePassLineChange = (value) => {
  // 直接接收输入值
  let numValue = parseFloat(value)
  
  // 检查是否为有效数字
  if (isNaN(numValue)) {
    numValue = 0.6 // 默认值
  }
  
  // 确保输入值在0-1之间
  numValue = Math.max(0, Math.min(1, numValue))
  
  // 限制为最多2位小数
  numValue = parseFloat(numValue.toFixed(2))
  
  console.log('DrawGoal: 更新达成标准为:', numValue)
  
  // 向父组件发送更新事件
  emit('update:achievementStandard', numValue)
  
  // 重新绘制散点图以更新及格线
  if (props.chartType === 'achievement-scatter') {
    nextTick(() => {
      drawScatterChart()
    })
  }
}

// 监听数据变化，重新绘制图表
watch(() => [props.goalResults, props.studentData, props.evaluationMethods, props.achievementStandard], () => {
  nextTick(() => {
    if (props.chartType === 'achievement-bar') {
      drawBarChart()
    } else if (props.chartType === 'achievement-scatter') {
      drawScatterChart()
    }
  })
}, { deep: true })

// 组件挂载时绘制图表
onMounted(() => {
  nextTick(() => {
    if (props.chartType === 'achievement-bar') {
      drawBarChart()
    } else if (props.chartType === 'achievement-scatter') {
      drawScatterChart()
    }
  })
})
</script>

<style scoped>
.draw-goal-container {
  width: 100%;
}

.chart-container {
  margin-bottom: 30px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chart-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: bold;
}

.chart {
  width: 100%;
  height: 600px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #ffffff;
}

.scatter-chart-item {
  margin-bottom: 30px;
}

.scatter-chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.scatter-chart-header h5 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: bold;
}

.scatter-chart {
  width: 100%;
  height: 600px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #ffffff;
}

.pass-line-setting {
  margin-bottom: 20px;
  padding-left: 10px; /* Align with form items */
}

.pass-line-form-item {
  margin-bottom: 0; /* Remove default margin */
}
</style>
